import React from 'react';
import ThemeCut from './components/theme-cut';
import { history, useModel } from 'umi';

import headerStyle from './index.less';
import {
  Avatar,
  Button,
  Dropdown,
  Form,
  Modal,
  Toast,
} from '@douyinfe/semi-ui';
import {
  IconBookmark,
  IconExit,
  IconHash,
  IconKey,
  IconMail,
  IconUser,
  IconUserGroup,
} from '@douyinfe/semi-icons';
import { clearToken, getToken, saveToken } from '../../unils/token';
import AuthUser from '../../api/model/users';

export default class Header extends React.Component {
  constructor(props: any) {
    super(props);
    this.state = {
      token: '',
      isUpdate: false,
    };
    this.switchMode = this.switchMode.bind(this);
    this.changeUpdate = this.changeUpdate.bind(this);
  }

  child: any;

  componentDidMount() {
    const token = getToken();
    this.setState({
      token,
    });
  }

  onLoginDialogRef(ref: any) {
    this.child = ref;
  }

  // 点击登陆按钮
  clickLoginBtn = (e: any) => {
    this.child.showLoginDialog();
  };

  // 暗黑/亮色模式切换
  switchMode(): any {
    const body = document.body;
    const themeMode = body.hasAttribute('theme-mode');
    if (themeMode) {
      body.removeAttribute('theme-mode');
    } else {
      body.setAttribute('theme-mode', 'dark');
    }
    this.setState({});
  }

  // 强制更新header
  changeUpdate() {
    const token = getToken();
    const { isUpdate }: any = this.state;
    this.setState({ isUpdate: !isUpdate, token });
  }

  // 返回主页
  goHome() {
    history.push('/');
  }

  // 跳转书签
  goBookmark() {
    history.push('/bookmark');
  }

  render() {
    const { token }: any = this.state;
    const iconStyle = {
      fontSize: '1.7rem',
      cursor: 'pointer',
      color: 'var(--semi-color-text-0)',
      marginRight: 12,
    };

    return (
      <>
        <div className={headerStyle.header_container + ' header_container'}>
          <h3 className={headerStyle.header_title} onClick={this.goHome}>
            Technique
          </h3>
          <div className={headerStyle.rigth_container}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ marginRight: 12 }}>
                <ThemeCut switchMode={this.switchMode} />
              </div>
              <div style={{ height: '24px' }} onClick={this.goBookmark}>
                <IconBookmark style={iconStyle} />
              </div>
              {!token ? (
                <Button
                  theme="solid"
                  type="secondary"
                  onClick={this.clickLoginBtn}
                >
                  登陆
                </Button>
              ) : (
                <AvatarInfo changeUpdate={this.changeUpdate} />
              )}
            </div>
          </div>
        </div>
        {/*  登陆对话框*/}
        <LoginDialog
          onLoginRef={(e: any) => this.onLoginDialogRef(e)}
          changeUpdate={this.changeUpdate}
        />
      </>
    );
  }
}

const AvatarInfo = (props: any) => {
  const { user }: any = useModel(
    'user',
    (model: { user: any; setuserInfo: any }) => ({
      user: JSON.parse(window.localStorage.getItem('userinfo') as string),
    }),
  );

  const layoutExit = () => {
    history.push('/');
    clearToken();
    props.changeUpdate();
  };

  const goAdminPage = () => {
    history.push('/admin');
  };

  const goUser = () => {
    history.push('/user');
  };

  return (
    <Dropdown
      trigger={'click'}
      position={'bottomLeft'}
      clickToHide={true}
      render={
        <Dropdown.Menu>
          <Dropdown.Item icon={<IconUser />} onClick={goUser}>
            个人中心
          </Dropdown.Item>
          <Dropdown.Item icon={<IconUserGroup />} onClick={goAdminPage}>
            后台管理
          </Dropdown.Item>
          <Dropdown.Item icon={<IconExit />} onClick={layoutExit}>
            退 出
          </Dropdown.Item>
        </Dropdown.Menu>
      }
    >
      <Avatar size="small" src={user.avatar} style={{ margin: 4 }} />
    </Dropdown>
  );
};

type Props = {
  onLoginRef: any;
  changeUpdate: any;
};

class LoginDialog extends React.Component<Props> {
  constructor(props: any) {
    super(props);
    this.state = {
      visible: false,
      register: false,
      title: '登陆',
      getEmailCode: '发送邮箱',
      isGetEmailCode: false,
      email: '',
    };
    this.showLoginDialog = this.showLoginDialog.bind(this);
    this.goRegister = this.goRegister.bind(this);
    this.handleOkLogin = this.handleOkLogin.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
    this.sendEmail = this.sendEmail.bind(this);
    this.changeEmail = this.changeEmail.bind(this);
  }

  componentDidMount() {
    this.props.onLoginRef(this);
  }

  showLoginDialog() {
    this.setState({
      visible: true,
    });
  }

  changeEmail(email: string) {
    this.setState({
      email,
    });
  }

  goRegister() {
    const { register }: any = this.state;
    this.setState({
      register: !register,
      title: register ? '登陆' : '注册',
    });
  }

  handleOkLogin() {
    this.setState({
      visible: false,
    });
    this.props.changeUpdate();
  }

  handleCancel(e: any) {
    this.setState({
      visible: false,
    });
  }

  async sendEmail(e: any) {
    const { email }: any = this.state;
    const match =
      /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
    if (!match.test(email)) {
      Toast.error({
        content: '请输入正确的邮箱！',
        duration: 3,
      });
    } else {
      const res: any = await AuthUser.SendEmail({ email });
      if (res.status) {
        Toast.success({
          content: '发送邮箱成功！',
          duration: 3,
        });
        let time = 59;
        let timer = setInterval(() => {
          if (time == 0) {
            clearInterval(timer);
            this.setState({
              isGetEmailCode: false,
              getEmailCode: '发送邮箱',
            });
          } else {
            this.setState({
              isGetEmailCode: true,
              getEmailCode: time + '秒后重试',
            });
            time--;
          }
        }, 1000);
      } else {
        Toast.error({
          content: res.data.error,
          duration: 3,
        });
      }
    }
  }

  render() {
    const { visible, title, register, getEmailCode, isGetEmailCode }: any =
      this.state;
    return (
      <>
        <Modal
          title={title}
          visible={visible}
          hasCancel={false}
          closable={false}
          footer={''}
          className="modalStyle"
          onCancel={this.handleCancel}
        >
          <div style={{ paddingBottom: '1rem' }}>
            <LoginForm
              handleOkLogin={() => {
                this.handleOkLogin();
              }}
              getEmailCode={getEmailCode}
              isGetEmailCode={isGetEmailCode}
              isregister={register}
              goRegister={this.goRegister}
              sendEmail={(e: any) => {
                this.sendEmail(e);
              }}
              changeEmail={(e: string) => {
                this.changeEmail(e);
              }}
            />
          </div>
        </Modal>
      </>
    );
  }
}

const LoginForm = (props: any) => {
  const { setuserInfo }: any = useModel(
    'user',
    (model: { user: any; setuserInfo: any }) => ({
      setuserInfo: model.setuserInfo,
    }),
  );
  const register = () => {
    props.goRegister();
  };
  // 验证规则
  const rules = (values: any) => {
    let isNext = true;
    const match =
      /^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/;
    if (!values.email || !values.password) {
      Toast.error({
        content: '请输入账号和密码！',
        duration: 3,
      });
      isNext = false;
    } else {
      if (props.isregister) {
        if (!values.verify_key) {
          Toast.error({
            content: '请输入验证码！',
            duration: 3,
          });
          isNext = false;
        } else {
          if (!match.test(values.email)) {
            Toast.error({
              content: '邮箱格式不正确！',
              duration: 3,
            });
            isNext = false;
          } else {
            if (values.password.length < 6) {
              Toast.error({
                content: '密码长度最少6位！',
                duration: 3,
              });
              isNext = false;
            }
          }
        }
      } else {
        if (!match.test(values.email)) {
          Toast.error({
            content: '请输入正确的邮箱！',
            duration: 3,
          });
          isNext = false;
        } else {
          if (values.password.length < 6) {
            Toast.error({
              content: '密码长度最少6位！',
              duration: 3,
            });
            isNext = false;
          }
        }
      }
    }
    return isNext;
  };

  // 发送邮箱
  const getEmailCodeBtn = () => {
    props.sendEmail();
  };

  // 登陆
  const handleSubmit = async (values: any) => {
    const next = rules(values);
    if (next) {
      let res: any = {};
      if (props.isregister) {
        const { email, password, verify_key } = values;
        res = await AuthUser.Register({ email, password, verify_key });
      } else {
        const { email, password } = values;
        res = await AuthUser.Login({
          email,
          password,
        });
      }
      if (res.status) {
        if (props.isregister) {
          Toast.success({
            content: '注册成功！',
            duration: 3,
          });
          props.goRegister();
        } else {
          Toast.success({
            content: '登陆成功！',
            duration: 3,
          });
          saveToken(res.data.token);
          setuserInfo(res.data.userInfo);
          props.handleOkLogin();
        }
      } else {
        Toast.error({
          content: res.data.error,
          duration: 3,
        });
      }
    }
  };
  return (
    <Form onSubmit={(values) => handleSubmit(values)} labelPosition="left">
      {({ formState, values, formApi }) => (
        <>
          {props.isregister ? (
            <div
              style={{ width: '100%', display: 'flex', alignItems: 'center' }}
            >
              <div style={{ width: '100%' }}>
                {/*// @ts-ignore*/}
                <Form.Input
                  onChange={(e) => {
                    props.changeEmail(e);
                  }}
                  noLabel={true}
                  prefix={<IconMail />}
                  showClear
                  field="email"
                  label="邮箱"
                  trigger="change"
                  placeholder="请输入邮箱账号"
                ></Form.Input>
              </div>
              <Button
                disabled={props.isGetEmailCode}
                onClick={getEmailCodeBtn}
                style={{ width: '30%' }}
                type="tertiary"
              >
                {props.getEmailCode}
              </Button>
            </div>
          ) : (
            // @ts-ignore
            <Form.Input
              onChange={(e) => {
                props.changeEmail(e);
              }}
              noLabel={true}
              prefix={<IconMail />}
              field="email"
              label="邮箱"
              style={{ width: '100%' }}
              trigger="change"
              placeholder="请输入邮箱账号"
            ></Form.Input>
          )}
          {props.isregister ? (
            // @ts-ignore
            <Form.Input
              prefix={<IconHash />}
              noLabel={true}
              field="verify_key"
              label="验证码"
              style={{ width: '100%' }}
              trigger="change"
              placeholder="请输入验证码"
            ></Form.Input>
          ) : (
            ''
          )}
          {/*// @ts-ignore*/}
          <Form.Input
            type="password"
            prefix={<IconKey />}
            noLabel={true}
            field="password"
            label="密码"
            style={{ width: '100%' }}
            trigger="change"
            placeholder="请输入密码"
          ></Form.Input>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <p>
              <span style={{ color: 'var(--semi-color-text-0)' }}>Or</span>
              <Button
                onClick={register}
                theme="borderless"
                style={{
                  color: 'var(--semi-color-primary)',
                  marginLeft: 10,
                  cursor: 'pointer',
                }}
              >
                {props.isregister ? '登 陆' : '注册'}
              </Button>
            </p>
            <Button htmlType="submit" type="tertiary">
              {!props.isregister ? '登 陆' : '注册'}
            </Button>
          </div>
        </>
      )}
    </Form>
  );
};
